package com.example.servlet;

import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet(name = "BuyBookServlet", urlPatterns = "/buy-book")
public class BuyBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookIdStr = req.getParameter("book_id");
        int bookId = -1;
        try {
            if (bookIdStr == null || bookIdStr.trim().isEmpty()) {
                resp.sendRedirect("/books");
                return;
            }
            bookId = Integer.parseInt(bookIdStr);
        } catch (NumberFormatException e) {
            resp.sendRedirect("/books");
            return;
        }
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement("UPDATE books SET clicks = clicks + 1 WHERE id = ?")) {
            ps.setInt(1, bookId);
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.sendRedirect("/books");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/books");
    }
} 